﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Filter;
using System.Linq.Expressions;
using COFE.Data.Utils;
using COFE.Data.Utils.ThirdParty;

namespace COFE.Data.Filter
{
    public class OrEntryFilterExpression :
         EntryFilterExpression<COFE.Core.Filter.OrEntryFilter>
    {
        public OrEntryFilterExpression()
            : base()
        {

        }

        static Expression<Func<T, bool>> OrElse<T>(
            Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2)
        {
            // need to detect whether they use the same
            // parameter instance; if not, they need fixing
            ParameterExpression param = expr1.Parameters[0];

            if (ReferenceEquals(param, expr2.Parameters[0]))
            {
                // simple version
                return Expression.Lambda<Func<T, bool>>(
                    Expression.OrElse(expr1.Body, expr2.Body), param);
            }
            // otherwise, keep expr1 "as is" and invoke expr2
            return Expression.Lambda<Func<T, bool>>(
                Expression.OrElse(
                    expr1.Body,
                    Expression.Invoke(expr2, param)), param);
        }


        public override Expression<Func<Entry, bool>> getExpression(
           IEntryFilter filter, IOptionFilter[] options)
        {
            var entryFilter = filter as COFE.Core.Filter.OrEntryFilter;

            Expression<Func<Entry, bool>> exp = null;

            foreach (var ef in entryFilter.EntryFilters)
            {
                var currentExp = DBFilterUtils.GetExpression(ef, options);
                if (exp == null)
                    exp = currentExp;
                else
                    exp = exp.Or(currentExp);
            }
           
            return exp;
        }



    }
}
